$NG.AllReady(function (page, { useValuesChange, useUpdateRows, useBeforeClick, useUpdateRow, useDataIndexChange, useClick }) {
  const mstform = $NG.getCmpApi("p_form_dev_cost_budget");
  const dgrid1 = $NG.getCmpApi("p_form_dev_labor_budget"); //研发人工
  const dgrid2 = $NG.getCmpApi("p_form_dev_daliy_budget");

  const toolbar = $NG.getCmpApi("toolbar");
  const toolbar_top = $NG.getCmpApi("toolbar_top");
  const toolbar_dgrid1 = $NG.getCmpApi("toolbar_" + "p_form_dev_labor_budget");
  const toolbar_dgrid2 = $NG.getCmpApi("toolbar_" + "p_form_dev_daliy_budget");

  const toolbars = [
    { toolbar: toolbar_dgrid1, items: ["", "", "imp", "attachment"] },
    { toolbar: toolbar_dgrid1, items: ["", "", "imp", "attachment"] },
  ];
  toolbars.forEach(({ toolbar, items }) => {
    if (toolbar && typeof toolbar.getItem === "function") {
      items.forEach((item) => {
        const button = toolbar.getItem(item);
        if (button) {
          button.setHidden(); // 隐藏按钮
        }
      });
    }
  });

  //添加按钮
  if (toolbar_dgrid2) {
    toolbar_dgrid2.insert({
      id: "fyadd",
      text: "选择费用项目",
      iconCls: "icon-New",
    });
    useClick(async function ({ args }) {
      Fyxm();
    }, "fyadd");
  }
  function Fyxm() {
    $NG.external
      .openNGHelp({
        type: "NGMultipleHelp",
        helpId: "cost_pc_ek",
        valueField: "phid",
        labelField: "u_name",
        clientSqlFilter: {
          u_sequence: "02",
        },
      })
      .then((data) => {
        try {
          if (Array.isArray(data) && data.length > 0) {
            var gridArr = [];
            for (var i = 0; i < data.length; i++) {
              var gridObj = {};
              gridObj.u_expense_code = data[i].origin.phid || "";
              gridObj.u_expense_code_EXName = data[i].origin.u_name || "";
              gridArr.push(gridObj);
            }
            console.log(gridArr);
            dgrid2.addRows(gridArr); // 将数据添加到表格组件中
            dgrid2.refreshView();
          } else {
            console.error("返回的数据无效或为空:", data);
          }
        } catch (error) {
          console.error("处理数据时出错:", error);
        }
      })
      .catch((error) => {
        console.error("打开NGHelp时发生错误:", error);
      });
  }

  useBeforeClick(async ({ args }) => {
    let lock = true;
    if (page.isList) {
      const phid = page.getSelectedRecord()[0].phid;
      await $NG.execServer("getSleftIsImport", { source: phid }, (res) => {
        if (res.count == 0) return;
        $NG.alert("已被设备清单引用，无法反审核！");
        lock = false;
      });
    }
    return lock;
  }, "applycheck");
  //判断合同下是否含有服务单
  getIsSelfOne();
  function getIsSelfOne() {
    if (page.oType != "add") return;
    const phid_pc = mstform.getItem("phid_pc").getValue();
    if (!phid_pc) return;
    $NG.execServer("getIsSelfOne", { phid_pc }, (res) => {
      console.log(res, "是否");
      const _data = JSON.parse(res.data)[0].extendObjects;
      console.log(_data.num, "数量");
      if (_data.num == 0) {
        window._addLock = false;
      } else {
        $NG.alert("合同下已存在二开费用单！");
        window._addLock = true;
      }
    });
  }
  // 设置默认值人民币和汇率
  if (page.oType == "add") {
    $NG.updateState((updater) => {
      updater.data.p_form_dev_cost_budget.setProps({
        phid_fcur: {
          label: "人民币",
          value: 1,
        },
        exchangerate: 1,
      });
    });
  }
  useBeforeClick(({ args }) => {
    if (window._addLock) {
      $NG.alert("合同下已存在二开费用单！");
      return false;
    } else {
      return true;
    }
  }, "save");
  useBeforeClick(({ args }) => {
    if (window._addLock) {
      $NG.alert("合同下已存在二开费用单！");
      return false;
    } else {
      return true;
    }
  }, "tempSave");
  useBeforeClick(({ args }) => {
    if (window._addLock) {
      $NG.alert("合同下已存在二开费用单！");
      return false;
    } else {
      return true;
    }
  }, "check");
  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  if (mstform) {
    console.log("mstform is ready");
    mstformUpdateUI();
    cntMFilter();
    getPtInfoByPhid();
    useValuesChange(({ args }) => {
      console.log(`项目监听`);
      mstform.getItem("u_cnt").setValue(null);
      getPtInfoByPhid();
      cntMFilter();
      getCntCount("p_form_dev_cost_budget", "u_cnt", () => {
        getCntInfo();
      });
    }, "p_form_dev_cost_budget.phid_pc");

    useValuesChange(({ args }) => {
      getCntInfo();
    }, "p_form_dev_cost_budget.u_cnt");
    getCntCount("p_form_dev_cost_budget", "u_cnt", getCntInfo);
    if (page.oType == "add") {
      mstform.getItem("bill_name").setValue((mstform.getItem("phid_pc").getText() || "") + "二开费用预算单");
      useValuesChange(({ args }) => {
        mstform.getItem("bill_name").setValue((mstform.getItem("phid_pc").getText() || "") + "二开费用预算单");
      }, "p_form_dev_cost_budget.phid_pc");
    }
    //表头多字段设置属性
    $NG.updateUI((updater) => {
      updater.fieldSetForm.p_form_dev_cost_budget.u_fitime.setProps({
        hidden: true, //隐藏
      });
    });
    setTimeout(() => {
      console.log(`校验隐藏的标识日期`, mstform.getItem("u_fitime").getValue());
    }, 1000);
  } else {
    console.error("mstform is not available");
  }

  function mstformUpdateUI(params) {
    //表头多字段设置属性
    // $NG.updateUI((updater) => {
    //   console.log(updater);
    //   updater.fieldSetForm.p_form_svc_cost_budget.PCFieldSetPanelGroup2.u_fitime.setProps({
    //     hidden: true, //隐藏
    //   });
    // });
  }

  if (!page.oType == "view") {
    getCntCount("p_form_dev_cost_budget", "u_cnt", () => {
      getCntInfo();
    });
  }

  ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////

  if (dgrid1) {
    useDataIndexChange(({ args, instance }) => {
      var items = args[0];
      if (items.u_position) {
        $NG.execServer("getSimpleDataByPhid", { phid: items.u_position }, function (res) {
          if (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            // 尝试将 c_descript 转换为数字
            const personnelRate = Number(datas.c_descript);
            if (isNaN(personnelRate)) {
              // 如果转换失败，可以设置一个默认值或者处理错误
              console.error("Invalid value for u_personnel_rate:", datas.c_descript);
            }
            items.u_personnel_rate = personnelRate;
            caculatedgrid();
          }
          dgrid1.refreshView();
        });
      }
      instance.updateRow(items);
    }, "p_form_dev_labor_budget.u_position");

    useUpdateRows(({ args }) => {
      caculatedgrid();
      var sumAmtOri = 0;
      const rows = args[0];
      rows.forEach((items) => {
        if (items.u_sxfs == 1) {
          sumAmtOri += parseFloat(items.u_labor_amt);
        }
      });
      //汇总赋值
      $NG.updateState((updater) => {
        updater.data.p_form_dev_cost_budget.setProps({
          u_zk: sumAmtOri,
        });
      });
      dgrid1.refreshView();
      dgrid1.getRows().forEach((items) => {
        if (!items.u_year) {
          items.u_year = new Date().getFullYear();
          items.u_year_EXName = new Date().getFullYear();
        }
      });
    }, "p_form_dev_labor_budget");
  }

  ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////

  if (dgrid2) {
    dgrid2UpdateUI();
    // 监听表格研发人工
    useUpdateRows(({ args }) => {
      console.log(`监听编辑`);
      caculatedgrid();
      dgrid2.getRows().forEach((items) => {
        if (!items.u_year) {
          items.u_year = new Date().getFullYear();
          items.u_year_EXName = new Date().getFullYear();
        }
      });
      dgrid2.refreshView();
    }, "p_form_dev_daliy_budget");

    // 暂时注释掉，不要删除！！！
    // 暂时注释掉，不要删除！！！
    // 暂时注释掉，不要删除！！！
    // 暂时注释掉，不要删除！！！
    // if (page.oType == "add") {
    //   $NG.execServer("getCostPc", { u_sequence: "03" }, (res) => {
    //     if (res.count == 0) return;
    //     const _data = JSON.parse(res.data);
    //     console.log(`费用项目`, _data);
    //     dgrid2.addRows(
    //       _data.reduce((value, item) => {
    //         const el = item.extendObjects;
    //         value.push({
    //           u_expense_code: el.phid,
    //           u_expense_code_EXName: el.u_name,
    //           // u_expense_description: el.u_describe,
    //         });
    //         return value;
    //       }, [])
    //     );
    //   });
    // }
  }

  function dgrid2UpdateUI(params) {
    $NG.updateUI((updater) => {
      if (updater.editGrid.p_form_dev_daliy_budget.u_expense_code) {
        updater.editGrid.p_form_dev_daliy_budget.u_expense_code.setProps({
          clientSqlFilter: {
            u_sequence: "02",
          },
        });
      }
    });
  }
  ////////////////////////////////////////////////////////////--mstform function--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--mstform function--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--mstform function--////////////////////////////////////////////////////////////
  // 获取项目信息
  function getPtInfoByPhid() {
    if (mstform.getItem("phid_pc").getValue()) {
      $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(`获取项目信息`, datas);
        //帮助字段赋值
        $NG.updateState((updater) => {
          updater.data.p_form_dev_cost_budget.setProps({
            u_pc_no: datas.pc_no, //项目编码
            //项目类型
            u_pc_type: {
              label: datas.type_name,
              value: datas.type_phid,
            },
            u_sqgw: {
              //售前顾问
              value: datas.user_sqgw_phid,
              label: datas.user_sqgw_name,
            },
            //事业部
            u_division: {
              value: datas.division_phid,
              label: datas.division_name,
            },
            u_regional_center: {
              //区域中心
              value: datas.regional_center_phid,
              label: datas.regional_center_name,
            },
            u_dept: {
              //部门
              value: datas.dept_phid,
              label: datas.dept_name,
            },
            phid_org: {
              //部门
              value: datas.org_phid,
              label: datas.org_name,
            },
            u_region: {
              //部门
              value: datas.dept_phid,
              label: datas.dept_name,
            },
            u_product_line: {
              //产品线
              value: datas.midwife_phid,
              label: datas.midwife_name,
            },
            u_agreed_sts_dt: datas.start_date, //计划完工日期
            u_agreed_pcl_dt: datas.end_date, //计划竣工日期
          });
        });
        // 判断是否是提前施工
        let lock = true;
        if(datas.user_sf_tqsg == '1'){
            lock = false
        } else {
            lock = true
        }
        console.log(`是否提前施工项目`,datas.user_sf_tqsg);
        $NG.updateUI((updater)=>{
                updater.fieldSetForm.p_form_dev_cost_budget.u_cnt.setProps({
                    required:lock
                })
            })
        getIsSelfOne()
      });
    }
  }
  // 获取合同信息
  function getCntInfo() {
    $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log(`合同：`, datas);
      //帮助字段赋值
      $NG.updateState((updater) => {
        updater.data.p_form_dev_cost_budget.setProps({
          // u_agreed_sts_dt: datas.start_dt, //计划完工日期
          // u_agreed_pcl_dt: datas.end_dt, //计划竣工日期
          u_cnt_no: datas.pcm_no,
          u_cnt_amt: datas.cnt_sum_fc,
          u_invoice_type: {
            label: datas.invoice_type_name,
            value: datas.invoice_type_phid,
          },
        });
      });
    });
    $NG.execServer("getCntPrivce", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
      try {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas?.cnt_sum_vat_fc, "获取合同金额");
        $NG.updateState((updater) => {
          updater.data.p_form_dev_cost_budget.setProps({
            u_cnt_amt_vat: datas?.cnt_sum_vat_fc,
          });
        });
      } catch (error) {}
      
    });
  }
  //获取合同数量
  function getCntCount(table, key, fun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
      console.log(res, "count");
      switch (res.count) {
        case 0:
          return;
        case 1:
          const datas = JSON.parse(res.data)[0].extendObjects;
          const temp_map = {};
          temp_map[key] = datas.phid;
          temp_map[`${key}_EXName`] = datas.bill_name;
          $NG.updateState((updater) => {
            updater.data[table].setProps({
              ...temp_map,
            });
            setTimeout(() => {
              if (fun) {
                fun();
              }
            }, 200);
          });
      }
    });
  }
  // 过滤合同
  function cntMFilter() {
    console.log(`开始过滤`);
    $NG.updateUI((updater, state) => {
      updater.fieldSetForm.p_form_dev_cost_budget.u_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG.getCmpApi("p_form_dev_cost_budget").getItem("phid_pc").getValue();
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG.getCmpApi("p_form_dev_cost_budget").getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            bill_type: 1,
            phid_pc: $NG.getCmpApi("p_form_dev_cost_budget").getItem("phid_pc").getValue(),
          },
        }),
      });
    });
  }

  ////////////////////////////////////////////////////////////--common function--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--common function--////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////--common function--////////////////////////////////////////////////////////////

  function caculatedgrid() {
    console.log(`监听生效`);
    let u_total_dgrid1 = 0;
    let u_total_dgrid2 = 0;
    let u_total_dgrid = 0; //合计总费用

    dgrid1.getRows().forEach((items, rowIndex) => {
      // 人工费合计=人员费率*数量*人月
      items.u_labor_amt_vat = (Number(items.u_personnel_rate) || 0) * (Number(items.u_qty) || 0) * (Number(items.u_per_amt_day) || 0);
      items.u_labor_amt = ((Number(items.u_personnel_rate) || 0) * (Number(items.u_qty) || 0) * (Number(items.u_per_amt_day) || 0)) / (1 + (Number(items.u_tax_rate) || 0));
      u_total_dgrid1 += parseFloat(items.u_labor_amt) || 0;
      dgrid1.refreshView();
    });
    dgrid2.getRows().forEach((items) => {
      let total = 0;
      for (let i = 1; i <= 12; i++) {
        const str = "u_expenses_" + String(i).padStart(2, "0");
        total += Number(items[str]) || 0;
      }
      items.u_dev_daliy_amt = total;
      u_total_dgrid2 += parseFloat(items.u_dev_daliy_amt);
      dgrid2.refreshView();
    });

    u_total_dgrid = u_total_dgrid1 + u_total_dgrid2;

    $NG.updateState((updater) => {
      updater.data.p_form_dev_cost_budget.setProps({
        u_total_labor_amt: u_total_dgrid1,
        u_total_daily_amt: u_total_dgrid2,
        u_total_dev_amt: u_total_dgrid,
      });
    });
  }

  if (page.oType == "add" || page.oType == "edit") {
    $NG.updateState((updater) => {
      updater.data.p_form_dev_cost_budget.setProps({
        u_fitime: "FY" + formatDate(new Date(), "yyyy-mm").replace("-", ".M"),
      });
    });
  }

  // 格式化日期
  function formatDate(dateStr, outputFormat) {
    const date = new Date(dateStr);

    if (isNaN(date)) {
      return "无效的日期字符串";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    let formattedDate;

    switch (outputFormat) {
      case "yyyy-mm-dd":
        formattedDate = `${year}-${month}-${day}`;
        break;
      case "yyyy-mm-dd HH:mm":
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
        break;
      case "yyyy-mm":
        formattedDate = `${year}-${month}`;
        break;
      // 可以根据需要继续添加其他格式的处理逻辑
      default:
        formattedDate = "不支持的输出格式";
    }

    return formattedDate;
  }
});

function getCntCount(table, key, fun) {
  if (!$NG.getCmpApi(table)) return;
  if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
  $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
    console.log(res, "count");
    switch (res.count) {
      case 0:
        return;
      case 1:
        const datas = JSON.parse(res.data)[0].extendObjects;
        const temp_map = {};
        temp_map[key] = datas.phid;
        temp_map[`${key}_EXName`] = datas.bill_name;
        $NG.updateState((updater) => {
          updater.data[table].setProps({
            ...temp_map,
          });
          setTimeout(() => {
            if (fun) {
              fun();
            }
          }, 200);
        });
    }
  });
}
